//axios封装
import axios from 'axios'
import axiosAdapterUniapp from 'axios-adapter-uniapp'

// const BASE_URL = 'http://192.168.1.7/index.php';
const BASE_URL = 'http://127.0.0.1/index.php'; 

//创建axios实例
const service = axios.create({
    baseURL: BASE_URL,
	// adapter: axiosAdapterUniapp, //适配真机访问【如小程序，移动设备等】todo 启用该配置导致本地浏览器访问
    timeout: 5000 //请求超时时间
})

//请求拦截器
service.interceptors.request.use(
    config => {
        //token相关操作
        let token = uni.getStorageSync("token")
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`
        } else {
			//跳转登录
			// uni.navigateTo({
			// 	url:'/pages/login/index'
			// })
		}
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

//响应拦截器
service.interceptors.response.use(
    response => {
        if (response.data.code !== 0) { //异常提示
			uni.showToast({
			    title: response.data.msg,
			    icon: 'error',
			    duration: 1000
			});
			//跳转登录
			uni.navigateTo({
				url:'/pages/login/index'
			})
        } else {
			return Promise.resolve(response.data) //返回所有内容
        }
    },
    error => {
        //处理HTTP错误状态码
        let message = ''
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    message = '认证失败，请重新登录'
                    break
                case 403:
                    message = '当前操作没有权限'
                    break
                case 404:
                    message = '资源不存在'
                    break
                case 500:
                    message = '服务器错误'
                    break
                default:
                    message = error.message
            }
        }
        return Promise.reject(error)
    }
)

//封装通用请求方法
export function request(options) {
    return service(options)
}

//封装GET请求
export function get(url, params, options = {}) {
    return service({
        url,
        method: 'get',
        params,
        ...options
    })
}

//封装POST请求
export function post(url, data, options = {}) {
    return service({
        url,
        method: 'post',
        data,
        ...options
    })
}

//其他请求方法同理可以继续封装...